package cn.cuilan.test.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock + Condition 方式实现
 *
 * @author zhangyan
 * @since 2023/3/10
 */
public class LockConditionPrint {

    private int num;
    private static final Lock lock = new ReentrantLock();
    private static final Condition c1 = lock.newCondition();
    private static final Condition c2 = lock.newCondition();
    private static final Condition c3 = lock.newCondition();
    private static final Condition c4 = lock.newCondition();

    public void print(int targetNum, String context,
                      Condition currentThread,
                      Condition nextThread) {
        for (int i = 0; i < 3; ) {
            // 先获得锁
            lock.lock();
            while (num % 4 != targetNum) {
                try {
                    currentThread.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ": " + context);
            num++;
            i++;
            // 唤醒下一个线程
            nextThread.signal();
            // 释放锁
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        LockConditionPrint lcp = new LockConditionPrint();

        new Thread(() -> lcp.print(0, "A", c1, c2), "Thread-a").start();
        new Thread(() -> lcp.print(1, "B", c2, c3), "Thread-b").start();
        new Thread(() -> lcp.print(2, "C", c3, c4), "Thread-c").start();
        new Thread(() -> lcp.print(3, "D", c4, c1), "Thread-d").start();
    }

}
